﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace ShareHelper
{
    /// <summary>
    /// 图片格式转换 压缩
    /// </summary>
    public static class ImageEncoders
    {
        private static ImageCodecInfo JpegICIinfo { get; }

        static ImageEncoders()
        {
            JpegICIinfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(a => a.FormatDescription == "JPEG");
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="iSource">图片类</param>
        /// <param name="flag">设置压缩的比例1-100</param>
        /// <returns></returns>
        public static byte[] TOJpg(Image iSource, int flag)
        {
            using (var data = new MemoryStream())
            {
                if (JpegICIinfo != null)
                {
                    EncoderParameters ep = new EncoderParameters();
                    ep.Param[0] = new EncoderParameter(Encoder.Quality, new long[] { flag });
                    iSource.Save(data, JpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                    iSource.Save(data, iSource.RawFormat);//dFile是压缩后的新路径
                return data.ToArray();
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="iSource">图片byte</param>
        /// <param name="flag">设置压缩的比例1-100</param>
        /// <returns></returns>
        public static byte[] TOJpg(byte[] iSource, int flag)
        {
            using (var ms = new MemoryStream(iSource))
            {
                using (Image img = Image.FromStream(ms, true))
                {
                    return TOJpg(img, flag);
                }
            }
        }
    }
}